package com.ypj.rpc.transport.netty.client;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 获取channel对象
 */
@Slf4j
public class ChannelProvider {

    //保存channel
    private final Map<String,Channel> channelMap;

    public ChannelProvider() {
        channelMap=new ConcurrentHashMap<>();
    }

    public Channel get(InetSocketAddress address){
        String key=address.toString();
        if (channelMap.containsKey(key)){
            Channel channel = channelMap.get(key);
            if (channel!=null&&channel.isActive()){
                return channel;
            }else {
                channelMap.remove(key);
            }
        }
        return null;
    }

    public void set(InetSocketAddress address,Channel channel){
        String key=address.toString();
        channelMap.put(key,channel);
    }

    public void remove(InetSocketAddress address){
        String key=address.toString();
        channelMap.remove(key);
    }
}
